'''
    Goblinoid: Experience all of MediaGoblin on an Android Device
    Copyright (C) 2015 Dylan Jeffers

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

# handles new user's login information
from __future__ import print_function
from os.path import join
from requests.exceptions import ConnectionError

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty
from kivy.uix.screenmanager import ScreenManager, SlideTransition

from goblinoid.services.login_service import create_pump_profile, \
    add_credential, verify_new_user
from pypump.exception import PyPumpException
Builder.load_file('screens/loginview.kv')

USER_DIR = join(App.get_running_app().user_data_dir, 'MediaGoblin')


# Screen manager to handle user input and error checking
class LoginManager(ScreenManager):
    webfinger = StringProperty()
    verifier_token = StringProperty()
    error_message = StringProperty()

    def check_webfinger(self):
        try:
            self.pump = create_pump_profile(self.webfinger)
            self.parent.parent.open_login_view('verify', False)
        except ConnectionError, e:
            print(e)
            error_message = 'data connection error, please try again later'
            self.set_error_message(error_message)
        except PyPumpException, e1:
            print(e1)
            error_message = 'Invalid webfinger, please try again'
            self.set_error_message(error_message)
        except IndexError, e2:
            print(e2)
            error_message = 'Webfinger missing @'
            self.set_error_message(error_message)

    def set_error_message(self, error_message):
        self.error_message = ''
        self.error_message = error_message

    def check_token(self):
        try:
            self.pump = verify_new_user(self.pump, self.verifier_token)
            print ('got through verification')
            self.parent.parent.open_login_view('enter', False)
            add_credential(USER_DIR, self.webfinger)
        except PyPumpException, e:
            print ('PyPumpException: {0}'.format(e))
            self.error_message = ''
            self.error_message = 'Verifier invalid, please try again'
        except KeyError, k:
            print ('KeyError: {0}'.format(k))
            self.error_message = ''
            self.error_message = 'Verifier invalid, please try again'

    # return user to home screen
    def return_to_homescreen(self):
        self.parent.parent.open_login_view('webfinger', True)

    def update_pump(self):
        App.get_running_app().pump_service.pump = self.pump
        self.current_screen.welcome_text = 'Welcome, press enter to continue'
        print ('pump updated')


class Login(Screen):
    lsm = ObjectProperty(LoginManager())

    webfinger = StringProperty()
    verifier_token = StringProperty()
    verified = BooleanProperty(False)

    def __init__(self, **kwargs):
        super(Login, self).__init__(**kwargs)
        self.user_dir = join(App.get_running_app().user_data_dir,
                             'MediaGoblin')
        print ('current app directory: {0}'.format(self.user_dir))
        self.transition = SlideTransition(duration=.35)
        self.lsm.transition = self.transition
        self.open_login_view('webfinger', False)

    # shuffles through login screen, verification screen, and enter screen
    def open_login_view(self, name, previous):
        print ('got to open_view: {0}, {1}'.format(name, previous))
        if self.lsm.has_screen(name):
            self.lsm.remove_widget(self.lsm.get_screen(name))
        # grabs screen from dictionary of screens
        screen = App.get_running_app().pump_service.screen_dict[name](name=name)
        self.lsm.add_widget(screen)
        if previous:
            self.transition.direction = 'right'
        else:
            self.transition.direction = 'left'
        self.lsm.current = screen.name

    # after user is verified, allow user to enter app
    def enter_app(self):
        App.get_running_app().open_view('action', False)


class WebFinger(Screen):
    webfinger = StringProperty()
    error_message = StringProperty()

    def on_error_message(self, instance, value):
        print ('webfinger got error message: {0}'.format(value))


class Verify(Screen):
    verifier_token = StringProperty()
    error_message = ObjectProperty()


class EnterApp(Screen):
    welcome_text = StringProperty('One moment while your profile is '
                                  'set up...')

    def on_enter(self):
        self.manager.update_pump()
